import React from 'react';
import { Menu, message } from 'antd';
import { BUSINESS_INF0, VEHICLE_INFO } from 'Constants/config';
import { connect } from 'react-redux';
import Api from 'Utils/api';
import './index.scss';

const $ = require('jquery');
/*eslintrc disabled*/

const { SubMenu } = Menu;
let isInitFinished = false;//视频插件是否加载完成
class VideoSysPage extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      hkData: null,
      jsession: sessionStorage.getItem('jsession') || '',
      vehicles: [],
      vehicleStatusArr: []
    };
    // 企业监控
    this.insertBusinessObj = ::this.insertBusinessObj;
    this.businessLogin = ::this.businessLogin;
    this.initHKBusiness = ::this.initHKBusiness;
    this.initHKCamera = ::this.initHKCamera;
    this.mergeCamerToHKdata = ::this.mergeCamerToHKdata;

    // 无人机
    this.initVehicleLogin = ::this.initVehicleLogin;
    this.initVehicleVideoPlugin = ::this.initVehicleVideoPlugin;
    this.initVehicleFlash = ::this.initVehicleFlash;
    this.initVehicleList = ::this.initVehicleList;
    this.handlevehicle = ::this.handlevehicle;
   // this.initHKBusiness = ::this.initHKBusiness;
  }
  componentWillUnmount() {
    clearTimeout(this.timer);
    if (document.getElementById('business-video').style.visibility === 'visible') {
      preview.StopPreview(-1);
    }
    if (window.player && document.getElementById('cmsv6flash').style.display === 'block') {
      window.player.stopVideo(0); // 停止播放无人机
    }
  }
  componentDidMount() {
    this.initVehicleLogin();
    this.insertBusinessObj();
    this.businessLogin();
    // 获取企业列表
    this.initHKBusiness();
  }
  // 企业监控
  insertBusinessObj() {
    document.getElementById('business-video').innerHTML = `
    <object classid="clsid:BE020CC9-521F-4641-85E1-3B631B7ADDD9" id="preview" width="100%" height="100%"  name="preview" >
       <PARAM NAME="Ip" VALUE="60.12.65.115"/>
       <PARAM  NAME="UserName " VALUE="admin"/>
       <PARAM  NAME="PrivilegeCode" VALUE="0401,0402,"/>
    </object> `;
  }
  businessLogin() {
    // 判断海康是否已经登录
    const param = `
    <?xml version="1.0" encoding="utf-8"?><LoginInfo><LoginType>2</LoginType><SynLogin>1</SynLogin><IP>${BUSINESS_INF0.ServerIP}</IP><Port>${BUSINESS_INF0.Port}</Port><UserName>${BUSINESS_INF0.UserName}</UserName><Password>${BUSINESS_INF0.PWD}</Password></LoginInfo>`;
    const res = preview.LoginPlat(param);
    if (res !== 0) {
      console.log('登录海康失败');
    }
    preview.SetLayoutType(1); // 设置窗格数
    document.getElementById('business-video').style.visibility = 'hidden';
  }
  initHKBusiness() {
    const api = new Api({
      method: 'GET',
      path: '/cameras/organization',
      success: (res) => {
        this.setState({
          hkData: res
        });
      },
      error: (error) => {
        console.log(error);
      }
    });
    api.run();
  }
  initHKCamera(indexCode) {
    const api = new Api({
      method: 'GET',
      path: '/cameras/camera_infos',
      query: {
        c_index_code: indexCode
      },
      success: (camera) => {
        this.mergeCamerToHKdata(indexCode, camera);
      },
      error: (err) => {
        console.log(err);
      }
    });
    api.run();
  }
  mergeCamerToHKdata(indexCode, camera) {
    const { hkData } = this.state;
    // 主控中心camera
    if (indexCode === hkData.c_index_code && hkData.camera) {
      return;
    }
    if (indexCode === hkData.c_index_code) {
      this.setState({
        hkData: { ...hkData, camera }
      });
    } else {
      // 子级组织下的camera
      this.subCamera(indexCode, camera);
    }
  }
  subCamera(indexCode, camera) {
    const { hkData } = this.state;
    const { sub_organizations } = hkData;
    const newOrg = sub_organizations.map((org) => {
      if (org.c_index_code === indexCode) {
        return {
          ...org,
          camera
        };
      }
      if (org.sub_organizations.length > 0 && this.checkIndexCode(org.sub_organizations, indexCode)) {
        const newSubOrg = org.sub_organizations.map((subOrg) => {
          if (subOrg.c_index_code === indexCode) {
            return {
              ...subOrg,
              camera
            };
          }
          return subOrg;
        });
        return {
          ...org,
          sub_organizations: newSubOrg
        };
      }
      return org;
    });
    this.setState({
      hkData: {
        ...hkData,
        sub_organizations: newOrg
      }
    });
  }
  // 检查该indexcode是否在给定的组织里边
  checkIndexCode(organise, indexCode) {
    const newOrg = organise.filter(item => item.c_index_code === indexCode);
    if (newOrg[0]) {
      return true;
    }
    return false;
  }
  // 无人机
  //init car list
  initVehicleList() {
    $.ajax({
      type: 'GET',
      url: `${VEHICLE_INFO.URL}/StandardApiAction_queryUserVehicle.action?jsession=${this.state.jsession}`,
      cache: false,
      dataType: 'JSONP',
      jsonp: 'callback',
      success: (res) => {
        if (res.result === 0) {
          this.setState({
            vehicles: res.vehicles
          }, () => {
            if (res.vehicles.length > 0) {
              this.getVehicleStatus();
            }
          });
        } else {
          message.warn('获取无人机列表失败');
        }
      }
    });
  }
  getVehicleStatus() {
    const { vehicles } = this.state;
    const vehicleStatusArr = [];
    for (let i = 0, len = vehicles.length; i < len; i++) {
      $.ajax({
        type: 'GET',
        url: `${VEHICLE_INFO.URL}/StandardApiAction_getDeviceStatus.action?jsession=${this.state.jsession}&devIdno=${vehicles[i].nm}&toMap=1`,
        cache: false,
        dataType: 'JSONP',
        jsonp: 'callback',
        success: (res) => {
          if (res.status) {
            const item = {
              id: vehicles[i].id,
              nm: vehicles[i].nm,
              status: parseInt(res.status[0].ol, 10) === 1 ? 1 : 0
            };
            vehicleStatusArr.push(item);
            if (i === len - 1) {
              this.setState({
                vehicleStatusArr
              });
            }
          }
        }
      });
    }
  }
  //init login
  initVehicleLogin() {
    console.log('login Vehicle');
    $.ajax({
      type: 'POST',
      url: `${VEHICLE_INFO.URL}/StandardApiAction_loginEx.action`,
      data: {
        account: VEHICLE_INFO.UserName,
        password: VEHICLE_INFO.PWD
      },
      cache: false,
      dataType: 'JSONP',
      jsonp: 'callback',
      success: (res) => {
        console.log(res);
        if (res.result === 0) {
          sessionStorage.setItem('jsession', res.jsession);
          this.setState({
            jsession: res.jsession
          }, () => {
            this.initVehicleList();
          });
          this.initVehicleVideoPlugin();
        } else {
          message.error('登入无人机失败');
        }
      },
    });
  }
  //初始化视频插件
  initVehicleVideoPlugin() {
    //视频插件初始化参数
    const params = {
      allowFullscreen: 'true',
      allowScriptAccess: 'always',
      bgcolor: '#ffffff',
      wmode: 'transparent'
    };
    //初始化flash
    const self = this;
    swfobject.embedSWF('static/player.swf', 'cmsv6flash', '100%', '100%', '11.0.0', null, null, params, null, (e) => {
      window.player = e.ref;
      setTimeout(() => { self.initVehicleFlash(); }, 1000);
    });
  }
  initVehicleFlash() {
    document.getElementById('cmsv6flash').style.display = 'none';
    const self = this;
    if (!window.player) {
      this.timer = setTimeout(() => { self.initVehicleFlash(); }, 5000);
      message.warn('初始化flash失败');
    } else {
      if (!window.player.setWindowNum) {
        return;
      }
      //设置视频插件的语言
      window.player.setLanguage('http://211.162.125.99:8080/808gps/open/player/cn.xml');
      //先将全部窗口创建好
      window.player.setWindowNum(36);
      //再配置当前的窗口数目
      window.player.setWindowNum(1);
      //设置视频插件的服务器
      window.player.setServerInfo('211.162.125.206', '6605');
      isInitFinished = true;
    }
  }
  //public for business && vehicles
  change(item) {
    const type = item.item.props.type;
    if (type === 'business') {
      if (document.getElementById('business-video').style.visibility === 'hidden') {
        document.getElementById('business-video').style.visibility = 'visible';
      }
      if (document.getElementById('cmsv6flash').style.display === 'block') {
        if (window.player) {
          window.player.stopVideo(0); // 停止播放
        }
        document.getElementById('cmsv6flash').style.display = 'none';
      }
      this.handleBusiness(item.item.props.code);
    } else if (type === 'vehicle') {
      if (isInitFinished) {
        if (document.getElementById('cmsv6flash').style.display === 'none') {
          document.getElementById('cmsv6flash').style.display = 'block';
        } else {
          // stop
          window.player.stopVideo(0);
        }
        if (document.getElementById('business-video').style.visibility === 'visible') {
          preview.StopPreview(-1);
          document.getElementById('business-video').style.visibility = 'hidden';
        }
        this.handlevehicle(item.item.props.code);
      } else {
        message.warn('flash初始化后查看视频');
      }
    }
  }
  handleBusiness(code) {
    const _param = `<?xml version="1.0" encoding="UTF-8"?><Preview><CamIndexCode>${code}</CamIndexCode></Preview>`;
    preview.StartPreview(_param);
  }
  handlevehicle(deId) {
    console.log(deId);
    if (isInitFinished) {
      console.log('test');
      // window title
      window.player.setVideoInfo(0, `无人机${deId}实时视频`);
      //play
      window.player.startVideo(0, this.state.jsession, deId, 0, 1, true);
      // buffer
      window.player.setBufferTime(0, 2);
    }
  }
  onTitleClick(camera, obj) {
    if (!camera) {
      this.initHKCamera(obj.key);
    }
  }

  renderHKsubOrg(data, titleImg = false) {
    const { camera, sub_organizations } = data;
    return (
      <SubMenu
        key={data.c_index_code}
        title={
          <span>{titleImg ? <img src="images/videoSys/icon_business_monitor.png" className="menu-icon" alt="企业监控" /> : '' }<span>{data.c_org_name}</span></span>
        }
        onTitleClick={this.onTitleClick.bind(this, camera)}
      >
        {
          sub_organizations.length > 0 ?
            sub_organizations.map(org => this.renderHKsubOrg(org))
            : ''
        }
        {
          camera && camera.length > 0 ? this.renderHKCamera(camera) : ''
        }
      </SubMenu>
    );
  }
  renderHKCamera(camera) {
    return (
      camera.map(item => (
        <Menu.Item key={item.c_index_code} className="submenu" type="business" code={item.c_index_code} status={item.on_line} disabled={!(item.on_line === 1)}>
          {
            item.on_line === 1 ? <img src="images/videoSys/icon_on.png" className="video-state" alt="" /> : <img src="images/videoSys/icon_off.png" alt="" className="video-state" />
          }
          {item.c_device_name}
        </Menu.Item>
      ))
    );
  }
  render() {
    const { vehicleStatusArr, hkData } = this.state;
    return (
      <div className="video-sys-wrapper" >
        <div className="video-sys-container">
          <div className="video-wrap">
            <div className="video">
              <div id="business-video" />
              <div className="vehicle-wrap">
                <div id="cmsv6flash" />
              </div>
            </div>
          </div>
          <div className="side-wrap">
            <div>
              <div className="video-menu">
                <div className="sys-menu">
                  <Menu
                    style={{ width: 240 }}
                    mode="inline"
                    theme="light"
                    onSelect={this.change.bind(this)}
                    defaultOpenKeys={['vehicle']}
                  >
                    {
                      vehicleStatusArr.length > 0 && <SubMenu key="vehicle" title={<span><img src="images/videoSys/icon_no_people.png" className="menu-icon" alt="无人机" /><span>无人机</span></span>}>
                        {
                          vehicleStatusArr.map(item => (
                            <Menu.Item key={item.nm} className="submenu" type="vehicle" code={item.nm} disabled={item.status === 0} >
                              {
                                item.status === 0 ? <img src="images/videoSys/icon_off.png" alt="" className="video-state" /> : <img src="images/videoSys/icon_on.png" className="video-state" alt="" />
                              }
                              无人机{item.nm}
                            </Menu.Item>
                          ))
                        }
                      </SubMenu>
                    }
                    {
                      hkData ? this.renderHKsubOrg(hkData, true) : ''
                    }
                  </Menu>
                </div>
              </div>
            </div>
          </div>
        </div>
      </div>
    );
  }
}
function mapStateToProps(state) {
  return {
    ...state.routing,
  };
}

export default connect(mapStateToProps)(VideoSysPage);
